<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/28 0028
 * Time: 16:11
 */
namespace app\index\controller;
use app\admin\model\ClockModel;
use app\admin\model\DepartmenModel;
use app\admin\model\LeaveModel;
use app\admin\model\NoticeModel;
use app\admin\model\PositionModel;
use app\admin\model\ProductsModel;
use app\admin\model\ReleaseModel;
use app\admin\model\ReportModel;
use app\admin\model\SettingModel;
use app\admin\model\SystemsModel;
use app\admin\model\UserModel;
use app\index\model\Api;
use app\index\model\UpFile;
use think\Db;
use think\Exception;
use think\helper\Time;
use think\Request;
use think\Validate;

class Add
{
    /**添加打卡记录，打卡api
     * @param Request $request
     * @return \think\response\Json
     */
    public function clock(Request $request){
        //获取打卡类型
        $type = $request->param('type',null);
        if(!$type){
            return json(['code'=>408,'msg'=>'请输入打卡类型']);
        }
        $user = isSign();
        if(!$user){
            return json(['code'=>401,'msg'=>'请先登录']);
        }
//        if(cache($user['id'].$type)){
//            return json(['code'=>405,'msg'=>'你已经打过这个卡了']);
//        }
        //获取打卡ip
        $ip = ip();
        //获取本部门打卡设置
        $setting = SettingModel::getSetting()->where(['card_setting.department_id'=>$user['department_id']])->find();
        if($ip!==$setting['wifi_ip']){
            return json(['code'=>402,'msg'=>'请链接打卡wifi']);
        }
        //组装数据存入打卡记录
        $data['userid'] = $user['id'];
        $data['company_id'] = $user['company_id'];
        $data['departmen_id'] = $user['department_id'];
        $data['punch_type'] = $type;
        $data['create_time'] = time();
        $work = date('w',time());
        //获取今天的开始时间戳和结束时间戳
        list($start,$end) = Time::today();
//        return $type;
        $jiou = ClockModel::getClock()
            ->where('punch_clock.userid',$user['id'])
            ->where('punch_clock.punch_type',$type)
            ->where('punch_clock.create_time','>',$start)
            ->where('punch_clock.create_time','<',$end)
            ->select();
        if($jiou){
            return json(['code'=>405,'msg'=>'你已经打过这个卡了']);
        }
        if(!in_array($work,$setting['attendance'])){
            return json(['code'=>999,'msg'=>'今天不上班,请联系你的领导']);
        }
//        return $type;
        //打上班卡
        if($type=='toWork'){
            //return json([time(),$start+$setting['late_time']]);
            //迟到
            if(time()>($start+$setting['work_shift'])&&time()<=($start+$setting['work_shift']+$setting['late_time'])){
                $data['late'] = 1;
            }
            //旷工
            if(time()>($start+$setting['work_shift']+$setting['late_time'])){
                $data['absenteeism'] = 1;
            }
        }elseif ($type=='offWork'){
            //早退
            if(time()<($start+$setting['closing_time'])){
                $data['early_retreat'] = 1;
            }
            //加班
            if(time()>($start+$setting['closing_time']+$setting['overtime'])){
                $data['overtime'] = 1;
            }
        }
        //添加打卡记录
        $bool = ClockModel::addClock($data);
        if($bool){
//            cache($user['id'].$type,'1',($end-time()));
            return json(['code'=>200,'msg'=>'打卡成功']);
        }else{
            return json(['code'=>205,'msg'=>'打卡失败,请等一分钟再试']);
        }
    }

    /**发布公告接口
     * @param Request $request
     * @return \think\response\Json
     */
    public function notice(Request $request){
        //检测登录
        $user = isSign();
        if(!$user){
            return json(['code'=>401,'msg'=>'请登录']);
        }
        $data = $request->param();
        $data['creat_time'] = time();
        //获取文件
        $file = UpFile::getFiles($request);
        if($file){
            $data['picture'] = $file['picture'];
        }
        if($data['type']=='com'){
            $data['notice_type'] = 0;
            //检测权限
            if(!Api::AuthIndex('添加公司公告')){
                return json(['code'=>403,'msg'=>'权限不足']);
            }
            //获取部门申明
            $data['affirming'] = (SystemsModel::getSystems()->where('id',1)->find())['value'];
        }else{
            $data['notice_type'] = $user['department_id'];
            //检测权限
            if(!Api::AuthIndex('添加部门公告')){
                return json(['code'=>403,'msg'=>'权限不足']);
            }
            //获取部门申明
            $data['affirming'] = $user['departmen_name'].$user['position_name'].'-'.$user['nickname'];
        }
        unset($data['type']);
        if(!$data['title']){
            return json(['code'=>408,'msg'=>'请输入标题']);
        }
        if(!$data['contents']){
            return json(['code'=>408,'msg'=>'请输入内容']);
        }
        $data['author'] = $user['id'];
        $data['readers'] = 0;
        //添加公告
        if(NoticeModel::addNotice($data)){
            return json(['code'=>200,'msg'=>'发布公告成功']);
        }else{
            return json(['code'=>407,'msg'=>'发布公告失败']);
        }
    }

    /**请假条添加
     * @param Request $request
     * @return array
     */
    public function leave(Request $request){
        $data = $request->param();
        //检测是否登录
        $user = isSign();
        if(!$user){
            return returns(401);
        }
        //获取的数据处理
        $data['starttime'] = strtotime($data['starttime']);
        $data['endtime'] = strtotime($data['endtime']);
        if(!$data['reason']||$data['reason']==' '){
            return returns(402,'请填写请假理由');
        }
        $data['time'] = time();
        $data['userid'] = $user['id'];
        $data['company_id'] = $user['company_id'];
        $data['departmen_id'] = $user['department_id'];
        $data['status'] = 0;
        if($filename = UpFile::getFiles($request)){
            $data['leave_picture'] = $filename['leave_picture'];
        }
//        return LeaveModel::addLeaveGetId($data);
        //消息添加
        $news['receive_id'] = $data['approver_id'];
        $news['send_out'] = $user['id'];
        $news['news_type'] = 'leave';
        $news['describe'] = $user['nickname'].'的请假条';
        $news['cretae_time'] = time();
        $news['status'] = 0;
        //添加请假条并获取所在id
        $bool = LeaveModel::addLeaveGetId($data);
        if($bool){
            $news['table_id'] = $bool;
        }else{
            return returns(405,'添加假条失败');
        }
        //添加消息
        if(Db::name('news')->insert($news)){
            return returns(200,'提交请假条成功');
        }else{
            return returns(408,'提交请假条失败');
        }
    }

    /**添加报告
     * @param Request $request
     * @return array
     */
    public function report(Request $request){
        $data = $request->param();
        //检测是否登录
        $user = isSign();
        if(!$user){
            return returns(401);
        }
        //处理数据
        if(!$data['contents']){
            return returns(405,'请填写报告内容');
        }
        if(!$data['work_report_title']){
            return returns(405,'请填写报告标题');
        }
        $data['author'] = $user['id'];
        $data['company_id'] = $user['company_id'];
        $data['department_id'] = $user['department_id'];
        $data['create_time'] = time();
        if($filename = UpFile::getFiles($request)){
            $data['picture'] = $filename['picture'];
        }
        //填写消息数据
        $news['receive_id'] = $data['recipient'];
        $news['send_out']   = $user['id'];
        $news['news_type']  = 'work_report';
        if($data['work_report_type']==1){
            $news['describe'] = $user['nickname'].'的工作日报';
        }elseif ($data['work_report_type']==2){
            $news['describe'] = $user['nickname'].'的工作周报';
        }elseif ($data['work_report_type']==3){
            $news['describe'] = $user['nickname'].'的工作月报';
        }
        $news['cretae_time'] = time();
        $news['status']      = 0;
        $bool = ReportModel::addReportGetId($data);
        if($bool){
            $news['table_id'] = $bool;
        }else{
            return returns(406,'添加报告失败');
        }
        if(Db::name('news')->insert($news)){
            return returns(200,'添加报告成功');
        }else{
            return returns(508,'添加报告失败');
        }
    }

    /**职位发布
     * @param Request $request
     * @return \think\response\Json
     */
    public function release(Request $request){
        $data = $request->param();
        if(!$user = isSign()){
            return returns(401);
        }
        if($user['departmen_name']!=='人事部'){
            return returns(402,'你权限不足');
        }
        $data['end_time'] = strtotime($data['end_time']);
        $data['company_id'] = $user['company_id'];
        $data['create_time'] = time();
        $department_id = PositionModel::getPosition()
            ->where('position_table.id',$data['position_id'])
            ->find();
        $data['department_id'] = $department_id['department_id'];
        $data['userid'] = $user['id'];
//            return json($department_id);
        if(ReleaseModel::addRelease($data)){
            return returns(200,'发布职位成功');
        }else{
            return returns(403,'发布职位成功');
        }
//        return json($data);
    }

    /**添加公司产品
     * @param Request $request
     * @return array
     */
    public function products(Request $request){
        $data = $request->param();
        if(!$user = isSign()){
            return returns();
        }
        //验证权限
        $authis = Api::AuthIndex('添加公司产品');
        if(!$authis){
            return returns(403,'权限不足');
        }
        //上传图片
        $file = UpFile::getFile($request);
        if($file){
            $data['picture'] = $file['picture'];
        }
        //验证字段
        $val= val($data,[
            'product_name|产品名称'=>'require',
            'picture|产品图片'     =>'require',
            'market_value|市场参考价'     =>'require',
            'required_integral|所需分数'     =>'require',
        ]);
        if(!$val['code']){
            return returns(403,$val['msg']);
        }
        $data['cretae_time'] = time();
        $data['status']      = 1;
        //添加产品
        if(ProductsModel::addProducts($data)){
            return returns(200,'添加产品成功');
        }else{
            return returns(403,'添加产品失败');
        }
    }

    /**增加积分
     * @param Request $request
     * @return array
     */
    public function change(Request $request){
        $data = $request->param();
        //检测是否登录
        if(!$user=isSign()){
            return returns(401);
        }
        //检测权限
        if(!Api::AuthIndex('发放积分')){
            return returns(403,'权限不足');
        }
        $val = val($data,[
            'userid|被加分人'=>'require',
            'number|分数'  =>'require',
            'change_describes|加分描述'=>'require'
        ]);
        if(!$val['code']){
            return returns(403,$val['msg']);
        }
        $jiafenuser = UserModel::getIndexUser()->where('user.id',$data['userid'])->find();
        if($jiafenuser['department_id']!==$user['department_id']){
            if($user['departmen_name']!=='行政部'){
                return returns(405,'你的权限不足');
            }
        }
        if($user['jurisdiction']<=$jiafenuser['jurisdiction']){
            return returns(403,'你的权限不足');
        }
        //检测部门分数是否足够
        $departmen = DepartmenModel::getDepartmen()->where('departmen_table.id',$user['department_id'])->find();
        if($departmen['departmen_integral']<$data['number']){
            return returns(406,'部门积分不足');
        }
        //获取接收人信息
        //积分变更记录表数据
        $data['company_id'] = $jiafenuser['company_id'];
        $data['department_id'] = $jiafenuser['department_id'];
        $data['operator'] = $user['id'];
        $data['create_time'] = time();
//消息表数据
        $news['receive_id'] = $jiafenuser['id'];
        $news['send_out']   = $user['id'];
        $news['news_type']   = 'integral_change';
        $news['describe']   = $user['nickname'].'为你加分'.$data['number'];
        $news['cretae_time']   = time();
        $news['status']   = 0;
        $jifen1 = $jiafenuser['integral']+$data['number'];
        $jifen2 = $departmen['departmen_integral']-$data['number'];
        Db::startTrans();
        try{
            //积分变更事务
            Db::name('user')->where('id',$jiafenuser['id'])->update(['integral'=>$jifen1]);
            Db::name('departmen_table')->where('id',$departmen['id'])->update(['departmen_integral'=>$jifen2]);
            $id = Db::name('integral_change')->insertGetId($data);
            if($id){
                $news['table_id'] = $id;
            }
            Db::name('news')->insert($news);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return returns(405,'积分变更失败');
        }
        return returns(200,'积分变更成功');
    }
}